<template>
  <div class="container">
    <el-row >
      <!-- <el-col :span="10" :offset="1">
        <el-scrollbar class="scrollbar">
          <el-form label-width="140px">
            <draggable :clone="cloneData" :list="form_list" :options="dragOptions1">
              <transition-group
                class="form-list-group"
                type="transition"
                name="list"
                tag="div"
              >
                <renders
                  v-for="(element,index) in form_list"
                  :key="index"
                  :ele="element.ele"
                  :obj="element.obj || {}"
                  renderPattern="example"
                ></renders>
              </transition-group>
            </draggable>
          </el-form>
        </el-scrollbar>
      </el-col> -->
      <el-col :span="10" :offset="1">
        <draggable :clone="cloneData" :list="form_list" :options="dragOptions1">
          <div v-for="(element,index) in form_list" :key="index" class="module">
                  {{element.name}}
          </div>
        </draggable>
      </el-col>
      <el-col :span="10" :offset="2">
        <el-scrollbar class="scrollbar2">
          <div class="tip" v-show="sortable_item.length == 0">请拖拽放入控件</div>
          <el-form
            ref="formValidate"
            label-width="auto"
            :model="formData"
            @submit.native.prevent
          >
            <draggable :list="sortable_item" :options="dragOptions2">
              <transition-group
                class="form-list-group"
                type="transition"
                name="list"
                tag="div"
              >
                <renders
                  @handleRemoveEle="removeEle"
                  @handleConfEle="confEle"
                  @clickHandler="clickHandler"
                  v-for="(element,index) in sortable_item"
                  :key="index"
                  :index="index"
                  :ele="element.ele"
                  :obj="element.obj || {}"
                  :sortableItem="sortable_item"
                  :config-icon="true"
                  renderPattern="config"
                ></renders>
              </transition-group>
            </draggable>
          </el-form>
        </el-scrollbar>
        <div style="text-align:center;margin-top:10px;">
          <el-button type="primary" @click="handleSubmit()">提交</el-button>
          <el-button type="ghost" @click="handleReset()" style="margin-left: 8px">清空</el-button>
        </div>
      </el-col>
    </el-row>
    <el-drawer
      size="500px"
      :modal="false"
      :visible.sync="showModal"
      :before-close="handleCancel"
      :with-header="false"
      direction="ltr"
      custom-class="demo-drawer"
      >
      <div class="demo-drawer__content">
        <div class="title">
          配置<span style="color:red;">{{ modalFormData.label }}</span>属性
        </div>
        <el-form
          class="form_content"
          label-width="110px"
          :model="modalFormData"
          ref="modalFormData"
          :rules="rules"
        >
          <TitleConfig v-if="modalFormData.type==='title'" :modalFormData="modalFormData"/>
          <HrConfig v-if="modalFormData.type==='hr'" :modalFormData="modalFormData"/>
          <BrConfig v-if="modalFormData.type==='br'" :modalFormData="modalFormData"/>
          <ButtonConfig v-if="modalFormData.type==='button'" :modalFormData="modalFormData"/>
          <PConfig v-if="modalFormData.type==='p'" :modalFormData="modalFormData"/>
          <SwitchConfig v-if="modalFormData.type==='switch'" :modalFormData="modalFormData"/>
          <SliderConfig v-if="modalFormData.type==='slider'" :modalFormData="modalFormData"/>
          <InputConfig v-if="modalFormData.type==='input'" :modalFormData="modalFormData"/>
          <SelectConfig v-if="modalFormData.type==='select'" :modalFormData="modalFormData"/>
          <RadioConfig v-if="modalFormData.type==='radio'" :modalFormData="modalFormData"/>
          <CheckBoxConfig v-if="modalFormData.type==='checkbox'" :modalFormData="modalFormData"/>
          <TextareaConfig v-if="modalFormData.type==='textarea'" :modalFormData="modalFormData"/>
          <DataPickerConfig v-if="modalFormData.type==='datepicker'" :modalFormData="modalFormData"/>
          <CascaderConfig v-if="modalFormData.type==='cascader'" :modalFormData="modalFormData"/>
          <UploadsConfig v-if="modalFormData.type==='uploads'" :modalFormData="modalFormData"/>
          <el-form-item>
            <el-button type="primary" :loading="modalFormData.loading" @click="handleOk">提交</el-button>
            <el-button @click="handleCancel">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import draggable from "vuedraggable";
import form_list from "./custom_form/FormList";
export default {
  components: {draggable},
  data() {
    var validateName = (rule, value, callback) => {
      if (this.modalFormData.name === this.modalFormOldName) {
        callback();
      }
      if (Object.keys(this.formData).includes(this.modalFormData.name)) {
        //如果当前的name字段与表单中其他name字段重复
        callback(new Error("不能与同表单其他控件的name重复！"));
      }
      callback();
    };
    return {
      form_list: form_list,
      sortable_item: [],
      showModal: false, // 显示弹框
      // 深拷贝对象，防止默认空对象被更改
      // 颜色选择器bug，对象下color不更新
      modalFormData: {
        color: "",
        loading: false
      },
      modalFormOldName: "", //当前控件的老名字
      dataDict: [],
      rules: {
        name: [
          { required: true, message: "请输入name", trigger: "blur" },
          { validator: validateName, trigger: "blur" }
        ]
      },
      selectList:[]
    };
  },

  methods: {
    clickHandler(btnName, ability) {
      if (ability == "submit") {
        //提交表单
        this.$refs["formValidate"].validate(valid => {
          if (valid) {
            console.log(this.formData);
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      } else if (ability == "reset") {
        this.$refs["formValidate"].resetFields();
        console.log(this.formData, "this.formData");
        this.sortable_item.forEach(item => {
          item.obj.value = null;
        });
        //重置表单
      }
    },
    // 克隆表单提交事件
    handleSubmit() {
      console.log(this.sortable_item);
      console.log(this.formData);
      this.$router.push({
        name: "renderForm",
        params: { sortable_item: JSON.stringify(this.sortable_item) }
      });
    },
    // 清空克隆表单
    handleReset() {
      this.sortable_item = [];
    },
    // https://github.com/SortableJS/Vue.Draggable#clone
    // 克隆,深拷贝对象
    cloneData(original) {
      // 深拷贝对象，防止默认空对象被更改
      let newOriginal = JSON.parse(JSON.stringify(original));
      newOriginal.obj.name = `key_${new Date().getTime()}` //设置默认名字
      console.log(original);
      return newOriginal
    },
    // modal点击确定执行事件
    handleOk() {
      console.log(this.modalFormData.name,this.modalFormOldName,11)
      this.$refs["modalFormData"].validate(valid => {
        if (valid) {
          console.log(this.modalFormData, "提交的数据");
          const index = this.modalFormData.listIndex;
          this.sortable_item[index].obj = Object.assign(
            {},
            this.sortable_item[index].obj,
            this.modalFormData
          );
          this.modalFormOldName = this.modalFormData.name
        }
      });
    },
    // modal点击取消执行事件，清空当前modal内容
    handleCancel() {
      this.showModal = false;
      setTimeout(_ => {
        this.modalFormData = {
          color: "",
          loading: false
        };
      }, 500);
    },
    // 显示modal,配置被克隆控件
    confEle(index) {
      const list_temp = Object.assign({}, this.sortable_item[index]);
      for (let i in list_temp.obj) {
        this.modalFormData[i] = list_temp.obj[i];
      }
      // 配置项中未找到color，删除modalFormData中自带color属性
      if (!list_temp.obj["color"]) delete this.modalFormData.color;
      // 设置被配置控件的index，便于完成配置找到相应对象赋值
      this.modalFormData.listIndex = index;
      // Vue 不能检测到对象属性的添加或删除
      this.modalFormData = Object.assign({}, this.modalFormData);
      this.showModal = true;
      if(this.$refs.modalFormData) this.$refs.modalFormData.clearValidate()
      this.modalFormOldName = this.modalFormData.name;
    },
    // 删除克隆控件
    removeEle(index) {
      let name = this.sortable_item[index].obj.name;
      this.sortable_item.splice(index, 1);
    },

    deleteDataList(index) {
      this.modalFormData.dataList.splice(index, 1);
    }
  },
  watch: {
    showModal(val) {
      if (!val) {
        this.handleCancel();
      }
    }
  },
  computed: {
    formData() {
      let obj = {};
      this.sortable_item.forEach(item => {
        if ("name" in item.obj) {
          obj[item.obj.name] = item.obj.value;
        }
      });
      return obj;
    },
    // 数据字典已选择项
    dataDictSelected() {
      return this.sortable_item.map(v => {
        const obj = JSON.parse(v.obj.dict || "{}");
        return obj.id || -1;
      });
    },
    // 对应控件的数据字典
    dataDictList() {
      return this.dataDict.filter(v => {
        return v.type == this.modalFormData.type;
      });
    },
    // 拖拽表单1
    dragOptions1() {
      return {
        animation: 0,
        ghostClass: "ghost",
        // 分组
        group: {
          name: "shared",
          pull: "clone", // 允许克隆
          revertClone: false // 不允许反克隆
        },
        // 禁止拖动排序
        sort: false
      };
    },
    // 拖拽表单2
    dragOptions2() {
      return {
        animation: 200,
        ghostClass: "ghost",
        group: {
          // 只允许放置shared的控件,禁止pull
          put: ["shared"]
        }
      };
    }
  },
};
</script>
<style>
.module{
  width:100px;
  height:40px;
  border:1px solid #f2f2f2;
  display: flex;
  justify-content: center;
  align-items: center;
}
.module:hover{
  background-color: #666;
  color:#fff;
}
.inline {
  display: inline-block;
}
.m-l-lg {
  margin-left: 30px;
}
.wrapper {
  padding: 15px;
}

.inline-block {
  display: inline-block;
}

.padder-sm {
  padding-right: 10px;
  padding-left: 10px;
}
.scrollbar{
  border: 1px solid #ccc;
  height:800px;
}
.scrollbar2{
  border: 1px solid #ccc;
  height:800px;
}
.el-select-dropdown__wrap{
  margin-bottom:0px!important;
}
.el-scrollbar__wrap {
    overflow-x: hidden!important;
}
.ghost {
  opacity: 0.5;
  background: #c8ebfb;
}

.form-list-group {
  min-height: 800px;
  padding: 30px !important;
}

/* 设置items下所有鼠标样式为 move */

.items,
.items * {
  cursor: move;
}
/* 配置按钮默认位置 */

/* 例如P Hr Title按钮 */

.items .item-icon {
  font-size: 16px;
  transition: all 2s ease;
  position: absolute;
  top: -30px;
  right: 0px;
  opacity: 0;
  max-height: 0;
  overflow: hidden;
}

.el-select{
  width:100%;
}
/* form控件下配置按钮位置 */

.ivu-form-item.items .item-icon {
  top: -25px;
}

/* 配置按钮样式 */

.item-icon i {
  cursor: pointer !important;
  margin-right: 5px;
}

.items:hover .item-icon {
  transition: inherit;
  opacity: 1;
  max-height: 50px;
}

/* 提交按钮下方无 margin-bottom */

/* .form_content .ivu-form-item:last-child {
  margin-bottom: 0;
} */

/* 表单校验选项样式 */

/* .ivu-form-item-required .ivu-form-item-label:before {
  content: "";
} */


.el-icon-circle-plus-outline,
.el-icon-remove-outline {
  font-size: 20px;
  color: #666;
}
.el-icon-circle-plus-outline:hover {
  color: green;
}
.el-icon-remove-outline:hover {
  color: red;
}
.el-icon-s-tools:hover {
  color: green;
}
.el-icon-error:hover {
  color: red;
}
.demo-drawer{
  padding:20px;
  text-align: left;
}
.el-select-dropdown__list .el-cascader-menu__list{
  margin-top:0;
  margin-bottom:16px;
}
.title{
  text-align:center;
  font-size:25px;
  width:100%;
  height:60px;
  line-height:60px;
  padding-bottom: 20px;
}
.tip{
  position: absolute;
  left:50%;
  top:50%;
  transform: translate(-105px,-21px);
  font-size: 30px;
  font-weight: 800;
  color:#888;
}
.list-move {
  transition: transform 0.5s;
}
.list-enter-active {
  transition: all 0.5s;
}
.list-leave-active {
  transition: all 0.5s;
  position: absolute;
}
.list-enter {
  opacity: 1;
  transform: translateY(30px);
}
 .list-leave-to {
  opacity: 0;
  transform: translateY(-30px);
}
/* 
::-webkit-scrollbar-track-piece { 
  background-color:#f8f8f8;
}
::-webkit-scrollbar {
  width:9px;
  height:9px;
}
::-webkit-scrollbar-thumb {
  background-color:#dddddd;
  background-clip:padding-box;
  min-height:28px;
}
::-webkit-scrollbar-thumb:hover {
  background-color:#bbb;
} */
</style>